package com.ruoyi.auth.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class AuthTokenUtils {

    private static final String SECRET_KEY = "123455667"; // 严禁修改此变量值

    /**
     * @throws
     * @Title: generateTicket
     * @Description: 生成ticket
     * @param: @param id
     * @param: @return
     * @return: String
     */
    public static String generateTicket(String id) {
        Map<String, Object> claims = new HashMap<>();
        String compactJws = Jwts.builder().setSubject(String.valueOf(id)).setId(UUID.randomUUID().toString().replaceAll("-", ""))
                .setIssuedAt(new Date()).addClaims(claims).signWith(SignatureAlgorithm.HS256, SECRET_KEY.getBytes(StandardCharsets.UTF_8)).compact();
        return compactJws;
    }

    /**
     * @throws
     * @Title: get_auth_token
     * @Description: 获取ticket信息
     * @param: @return
     * @return: String
     */
    public static String get_auth_token() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String headerAuthorization = request.getHeader("authorization"); // 获取认证数据
        if (StringUtils.isNotBlank(headerAuthorization) && headerAuthorization.startsWith("Bearer")) {
            return headerAuthorization.substring(7);
        } else {
            return "";
        }
    }

    /**
     * @throws
     * @Title: get_decode_auth_id
     * @Description: 解析ticket信息
     * @param: @param jws
     * @param: @return
     * @return: String
     */
    public static String get_decode_auth_id(String jws) {
        Claims clms = null;
        try {
            clms = Jwts.parser().setSigningKey(SECRET_KEY.getBytes(StandardCharsets.UTF_8)).parseClaimsJws(jws).getBody();
        } catch (SignatureException se) {
            try {
                clms = Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(jws).getBody();
            } catch (SignatureException se2) {
                return "";
            }
        }
        return clms.getSubject();
    }

}
